<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Import extends CI_Controller {
	function Import()
	{
		parent::__construct();
		// load language file
		$this->lang->load('i18n');
		$this->load->config('config');
		$this->load->helper('url');
		
		$loggedIn = $this->session->userdata('loggedIn');
		$role = $this->session->userdata('role');
		if(empty($loggedIn) && $role != ROLE_ADMIN && $this->router->fetch_method() != 'error'){
			$this->session->set_flashdata("errors", array($this->lang->line('lang.import.logginRequired')));
			redirect($this->lang->languageCode().'/import/error', 'location');
		}
	}
	
	var $affectedRowsKey = "affectedRows";

	public function index()
	{
		// Charge the view inside array
		$data = array();
		$data['content'] = $this->load->view('import-content.phtml', null , true);
		
		$data['import_selected_class'] = "current";
		$this->load->view('mainpage.phtml', $data);
	}
	
	public function error(){
		$data = array();
		$data['content'] = $this->load->view('error-content.phtml', null, true);
		$this->load->view('mainpage.phtml', $data);
	}

	public function do_import(){
		$uploadConfig['upload_path'] = $this->config->item('upload_path');
		$uploadConfig['max_filename'] = $this->config->item('max_filename');
		$uploadConfig['allowed_types'] = $this->config->item('allowed_types');
		$uploadConfig['remove_spaces'] = $this->config->item('remove_spaces');
		$uploadConfig['overwrite'] = $this->config->item('overwrite');
		$uploadConfig['ignore_mime'] = true;
		
		$this->load->library('upload', $uploadConfig);

		if (!$this->upload->do_upload("dulieucanxe"))
		{
			$this->session->set_flashdata("errors", array($this->lang->line('lang.import.fileError')));
			redirect($this->lang->languageCode().'/import/error', 'location');
		}
		else
		{
			$data = $this->upload->data();
			$uploadedFullPath = $data['full_path'];
			
			// Read and save data to db.
			$fileData = $this->readDbFFile($uploadedFullPath);
			$this->saveDataToDatabase($fileData["records"]);
		}

	}
	protected function readDbFFile($dbfname){
		/* load the required classes */
		require_once "./application/libraries/Column.class.php";
		require_once "./application/libraries/Record.class.php";
		require_once "./application/libraries/Table.class.php";
		$this->load->config('config');
		$data = array();
		
		/* create a table object and open it */
		$table = new XBaseTable($dbfname);
		$table->open();
		
		/* print some header info */
		$data["version"] = $table->version;
		$data["foxpro"] = $table->foxpro?"yes":"no";
		$data["recordCount"] = $table->recordCount;
		$data["headerLength"] = $table->headerLength;
		$data["recordByteLength"] = $table->recordByteLength;
		
		// Checking column header is the same with expected one.
		$expectedFields = $this->config->item('allowed_expected_fields');
		foreach($table->getColumns() as $i=>$c){
			if(in_array(strtolower($c->getName()), $expectedFields) == false){
				$this->session->set_flashdata("errors", array($this->lang->line('lang.import.columnInvalid')));
				redirect($this->lang->languageCode().'/import/error', 'location');
			}
		}
		
		/* get records data*/
		$records = array();
		$this->load->helper('date');
		$importFields = $this->config->item('allowed_import_fields');
		while ($record=$table->nextRecord()) {
			$dulieucanxe = array();
			foreach ($table->getColumns() as $i=>$c) {
				// Consider only fields which is in accepted fields list.
				$columnName = strtolower($c->getName()); 
				if(in_array($columnName, $importFields) == true){
					if($c->getType() == 'T'){
						$dulieucanxe["$columnName"] = date_to_mysqldatetime(date("d-m-Y H:i", $record->getDateTime($c)));//date_to_mysqldatetime($record->getDateTime($c), true);//date("d-m-Y H:i", $record->getDateTime($c));
					} else {
						$dulieucanxe["$columnName"] = mb_convert_encoding($record->getString($c), 'utf-8');
					}	
				}
			}
			array_push($records, $dulieucanxe);
		}
		$data['records'] = $records;
		/* close the table */
		$table->close();
		
		return $data;
	}
	
	/**
	 * This method will save records which is imported before to database.
	 * @param unknown_type $records
	 */
	protected function saveDataToDatabase($records){
		if(isset($records)){
			$this->db->trans_start(true);
			// Get all users from db.
			$current_users = $this->getUsersInArray();
			$count = 0;
			
			foreach($records as $record){
				$current_users = $this->pushNewUserIfNecessary($current_users, $record['cust_code'], $record['cust_name']);
				
				$count += $this->db->insert('dulieucanxe', $record); 
			}
			
			$this->insertNewUsers($current_users);
			$this->db->trans_complete();
			
			// Check error.
			if ($this->db->trans_status() === FALSE)
			{
				$this->session->set_flashdata("errors", array($this->lang->line('lang.import.saveError')));
				redirect($this->lang->languageCode().'/import/error', 'location');
			}
			// Redirect and show the number of rows is inserted.
			$this->session->set_flashdata("$this->affectedRowsKey", $count);
			redirect($this->lang->languageCode().'/import/', 'location');
		}
		return true; // If nothing is saved, tell true as the result.
	}
	
	protected function pushNewUserIfNecessary($current_users, $cust_code, $cust_name){
		if(!$this->checkUserExisted($current_users, $cust_code)){
			array_push($current_users, array('USER_ID' => '', 
											 'USERNAME' => $cust_code, 
											 'NAME' => $cust_name, 
											 'PASSWORD' => $cust_code,
											 'ROLE' => ROLE_CUSTOMER));
		}
		return $current_users;
	} 
	
	protected function checkUserExisted($current_users, $cust_code){
		foreach($current_users as $user){
			$existed = array_search($cust_code, $user);
			if(!empty($existed)){
				return true;
			}
		}
		return false;
	}
	
	protected function getUsersInArray(){
		$user_in_array = array();
		$current_users = $this->db->get('user')->result();
		foreach($current_users as $user){
			array_push($user_in_array, get_object_vars($user));
		}
		return $user_in_array;
	}
	
	protected function insertNewUsers($users){
		foreach($users as $user){
			if(empty($user['USER_ID'])){
				unset($user['USER_ID']); 
				$this->db->insert('user', $user); 
			}
		}
	}
}

/* End of file import.php */
/* Location: ./application/controllers/import.php */